package com.yugao.fintech.antelope.mps.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.antelope.mps.assembly.MsgFieldAssembly;
import com.yugao.fintech.antelope.mps.manager.MsgFieldManager;
import com.yugao.fintech.antelope.mps.mapper.MsgFieldMapper;
import com.yugao.fintech.antelope.mps.model.entity.MsgField;
import com.yugao.fintech.antelope.mps.model.rqrs.field.MsgFieldResp;
import com.yugao.fintech.antelope.mps.model.rqrs.field.MsgFieldSaveReq;
import com.yugao.fintech.antelope.mps.service.MsgFieldService;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MsgFieldServiceImpl extends ServiceImpl<MsgFieldMapper, MsgField> implements IService<MsgField>, MsgFieldService {
    @Autowired
    private MsgFieldManager msgFieldManager;
    @Autowired
    private MsgFieldAssembly msgFieldAssembly;

    
    @Override
    public List<MsgFieldResp> listMsgField(Long taskId) {
        if (Objects.isNull(taskId)) {
            return Collections.emptyList();
        }
    	return this.list(MsgField.lqw().eq(MsgField::getTaskId, taskId)).stream()
    	        .map(msgFieldAssembly::toMsgFieldResp).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSaveMsgField(Long taskId, List<MsgFieldSaveReq> req) {
        List<MsgField> list = req.stream().map(msgFieldAssembly::toMsgField).peek(e -> e.setTaskId(taskId))
                .collect(Collectors.toList());
        // 校验字段名是否重复
        Map<String, Integer> fieldCount = new HashMap<>();
        list.stream().map(MsgField::getFieldName).forEach(e -> {
            int count = fieldCount.getOrDefault(e, 0) + 1;
            if (count > 1) {
                throw new BizException("字段 {} 重复", e);
            }
            fieldCount.put(e, count);
        });

        this.remove(MsgField.lqw().eq(MsgField::getTaskId, taskId));
    	return this.saveBatch(list);
    }


    @Override
    public boolean deleteMsgField(Long taskId) {
        if (Objects.isNull(taskId)) {
            return false;
        }
    	return this.remove(MsgField.lqw().eq(MsgField::getTaskId, taskId));
    }
}
